/*******************************************************
 * @Title: ThreadMdcUtil
 * @ProjectName: AgileFastFK2.5
 * @Package: com.caltco.cargo.ops.interceptor
 * @Description: TODO
 * @author: daixirui
 * @version: V1.0.0
 * @Copyright: 2021 All rights reserved.
 * @date 2021/10/14 11:00</br>
 ********************************************************
 * @date 2021/10/14 11:00
 * @Title: 创建类
 * @version V1.0.0
 * @Description: TODO
/******************************************************/
package com.caltco.cargo.ops.common.interceptor;

import org.slf4j.MDC;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;

public class ThreadMdcUtil {
    public static void setTraceIdIfAbsent() {
        if (MDC.get("logsessionId") == null) {
            String uuid= UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
            uuid=uuid.substring(uuid.length()-8,uuid.length());
            MDC.put("logsessionId", uuid);
        }
    }

    public static <T> Callable<T> wrap(final Callable<T> callable, final Map<String, String> context) {
        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setTraceIdIfAbsent();
            try {
                return callable.call();
            } finally {
                MDC.clear();
            }
        };
    }

    public static Runnable wrap(final Runnable runnable, final Map<String, String> context) {
        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setTraceIdIfAbsent();
            try {
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }
}